package gwtappcontainer.client;

import java.io.Serializable;
import java.util.HashMap;

@SuppressWarnings("serial")
public class HistoryToken implements Serializable {
	public String appName = "";
	public String view = ""; //not used - see if it can be removed. (sathya, 25-sep-13)
	public HashMap<String, String> params = new HashMap<String, String>();	
	
	public HistoryToken(String historyToken) {
		
		if (historyToken.equals("")) {
			appName = "home";
			view = "";
		}
		
		String[] split = historyToken.split("/");
		appName = split[0];
		
		if (split.length > 1) {
			String viewParams = split[1];
			
			split = viewParams.split("\\?"); // ? is a reserver regex character, so 
											 // needs to be escaped
			view = split[0];
					
			if (split.length > 1) {
				String paramString = split[1];				
				String[] keyValueArray = paramString.split("&");
				
				for (String keyValue : keyValueArray) {
					split = keyValue.split("=");
					
					String key = split[0];
					String value = "";				
					if (split.length > 1) value = split[1];
					
					params.put(key, value);
				}
			}
		}							
	}
	
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("app = " + appName + ", ");
		sb.append("view = " + view + ", ");
		sb.append("params = ");
		
		for (String key : params.keySet()) {
			String value = params.get(key);
			sb.append("{" + key + ", " + value + "}, ");
		}
		
		return sb.toString();
	}
	
	public String getParamsAsString() {
		StringBuilder sb = new StringBuilder();
						
		for (String key : params.keySet()) {
			String value = params.get(key);
			sb.append(key + "=" + value + "&");
		}
		
		String s = sb.toString();
		
		//remove trailing & if it exists				
		if (s.length() > 0 && (s.charAt(s.length()-1) == '&')) {
			s = s.substring(0,  s.length()-1);
		}
				
		return s;
	}
}
